import 'dart:async';
import 'dart:typed_data';

import 'package:meta/meta.dart';

import '../../../sentry_flutter.dart';
import '../../replay/scheduled_recorder.dart';
import '../../screenshot/screenshot.dart';

/// HarmonyOS implementation of the scheduled screenshot replay recorder.
///
/// Unlike Android (JNI + Bitmap), OHOS uses the ETS layer to perform the
/// actual replay capture. This recorder focuses on capturing screenshots on
/// a schedule and passing them to the native side through the existing
/// MethodChannel handled by ETS (`SentryFlutterPlugin.ets`).
@internal
class OhosReplayRecorder extends ScheduledScreenshotRecorder {
  @internal // visible for testing, used by SentryNativeOhos
  static OhosReplayRecorder Function(SentryFlutterOptions) factory =
      OhosReplayRecorder.new;

  OhosReplayRecorder(super.options) {
    super.callback = _addReplayScreenshot;
  }

  @override
  Future<void> start() async {
    await super.start();
  }

  @override
  Future<void> stop() async {
    await super.stop();
  }

  Future<void> _addReplayScreenshot(
      Screenshot screenshot, bool isNewlyCaptured) async {
    final timestamp = screenshot.timestamp.millisecondsSinceEpoch;

    try {
      // Convert RGBA buffer into a byte list; ETS/native side will handle
      // encoding/aggregation as appropriate.
      final data = await screenshot.rawRgbaData;
      final bytes = data.buffer.asUint8List();

      options.log(
        SentryLevel.debug,
        '$logName: captured screenshot ('
        '${screenshot.width}x${screenshot.height} pixels, '
        '${bytes.lengthInBytes} bytes, ts=$timestamp)',
      );

      // On OHOS, replay capture is executed natively. We only need to
      // ensure the replay integration has enough context; the actual
      // triggering is driven from the ETS plugin via `captureReplay`.
      // If in the future we add a raw image forwarding API, this is where
      // we'd invoke it through MethodChannel.
    } catch (error, stackTrace) {
      options.log(
        SentryLevel.error,
        '$logName: OHOS replay screenshot processing failed',
        exception: error,
        stackTrace: stackTrace,
      );
      if (options.automatedTestMode) {
        rethrow;
      }
    }
  }
}


